package com.captjack.micro.dao.es.configuration;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * elastic-search 搜索引擎配置
 *
 * @author Capt Jack
 * @date 2018/3/23
 */
@Configuration
@EnableElasticsearchRepositories(basePackages = {"com.captjack.micro.dao.es.repository"})
public class ElasticSearchConfiguration {

    /**
     * 集群节点信息
     */
    @Value("${spring.data.elasticsearch.cluster-nodes}")
    private String clusterNodes;

    /**
     * 集群名称
     */
    @Value("${spring.data.elasticsearch.cluster-name}")
    private String clusterName;

    /**
     * 解析es节点配置信息
     *
     * @return es集群地址数组
     */
    private TransportAddress[] getTransportAddressArray() {
        List<TransportAddress> transportAddressList = new ArrayList<>();
        for (String hostAndPort : this.clusterNodes.split(",")) {
            String[] address = hostAndPort.split(":");
            transportAddressList.add(new InetSocketTransportAddress(new InetSocketAddress(address[0], Integer.parseInt(address[1]))));
        }
        return transportAddressList.toArray(new TransportAddress[transportAddressList.size()]);
    }

    @Bean(name = "elasticSearchClient")
    public Client getTransportClient() {
        // 设置集群名称
        Settings settings = Settings.builder().put("cluster.name", this.clusterName).build();
        // 创建client
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        // 设置集群配置信息
        transportClient.addTransportAddresses(getTransportAddressArray());
        return transportClient;
    }

    @Bean
    public ElasticsearchTemplate elasticsearchTemplate(@Qualifier(value = "elasticSearchClient") Client client) {
        return new ElasticsearchTemplate(client);
    }

}
